package com.tang.juc.container.unsafe;

import java.util.*;
import java.util.concurrent.CopyOnWriteArraySet;

/**
 * @author tlm
 * @version 1.0
 * @date 2020/4/21 17:33
 * 集合不安全问题之Set不安全
 */
public class SetUnsafeDemo {
    public static void main(String[] args) {
        //依然会发生 java.util.ConcurrentModificationException 并发修改异常
        Set<String> set = new HashSet<>();
        for (int i = 1; i <= 30; i++) {
            new Thread(() -> {
                set.add(UUID.randomUUID().toString().substring(0, 8));
                System.out.println(set);
            }, String.valueOf(i)).start();
        }

        //解决方案1： Collections.synchronizedSet(new HashSet<>());
        Set<String> set1 = Collections.synchronizedSet(new HashSet<>());
        //解决方案2： juc下的CopyOnWriteArraySet  (底层仍然是CopyOnWriteArrayList)
        Set<String> set2 = new CopyOnWriteArraySet<>();
    }
}
